import router from '@/router'
import { useUserInfoStore } from './stores/userInfo'
import getPageTitle from '@/utils/get-page-title'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
//隐藏右上角小圆圈
NProgress.configure({ showSpinner: false })
//白名单
const whiteList = ['/login', '/404']

//全局前置路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()

  //设置页面标题
  document.title = getPageTitle(to.meta.title as string)
  const userInfoStore = useUserInfoStore()
  const token = userInfoStore.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      const hasLogin = userInfoStore.userInfo.name
      if (hasLogin) {
        next()
      } else {
        try {
          await userInfoStore.getInfo()
          next(to)
        } catch (error) {
          await userInfoStore.reset()
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    //判断访问的是否是白名单
    if (whiteList.includes(to.path)) {
      next()
      NProgress.done()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from, next) => {
  NProgress.done()
})
